// 生成随机密钥
export async function generateRandomKey() {
  const key = await crypto.subtle.generateKey(
    { name: 'AES-GCM', length: 256 },
    true,
    ['encrypt', 'decrypt']
  );
  const exported = await crypto.subtle.exportKey('raw', key);
  return Array.from(new Uint8Array(exported))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}

// AES-GCM 加密
export async function encrypt(text, keyHex) {
  try {
    // 确保输入的十六进制字符串长度正确
    if (keyHex.length !== 64) { // 256位 = 32字节 = 64个十六进制字符
      throw new Error('Invalid key length');
    }

    const encoder = new TextEncoder();
    const keyBuffer = new Uint8Array(keyHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));
    const iv = crypto.getRandomValues(new Uint8Array(12)); // 96位 IV
    
    const cryptoKey = await crypto.subtle.importKey(
      'raw',
      keyBuffer,
      'AES-GCM',
      false,
      ['encrypt']
    );

    const encrypted = await crypto.subtle.encrypt(
      { name: 'AES-GCM', iv },
      cryptoKey,
      encoder.encode(text)
    );

    const encryptedArray = Array.from(new Uint8Array(encrypted));
    const ivArray = Array.from(iv);

    return {
      encrypted: encryptedArray.map(b => b.toString(16).padStart(2, '0')).join(''),
      iv: ivArray.map(b => b.toString(16).padStart(2, '0')).join('')
    };
  } catch (error) {
    console.error('Encryption error:', error);
    throw error;
  }
}

// AES-GCM 解密
export async function decrypt(encryptedHex, ivHex, keyHex) {
  try {
    console.log('decrypt params:', { encryptedHex, ivHex, keyHex });
    
    // 确保输入的十六进制字符串长度正确
    if (keyHex.length !== 64) { // 256位 = 32字节 = 64个十六进制字符
      throw new Error('Invalid key length');
    }
    if (ivHex.length !== 24) { // 96位 = 12字节 = 24个十六进制字符
      throw new Error('Invalid IV length');
    }

    // 从十六进制字符串导入密钥
    const keyBuffer = new Uint8Array(keyHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));
    const cryptoKey = await crypto.subtle.importKey(
      'raw',
      keyBuffer,
      'AES-GCM',
      false,
      ['decrypt']
    );

    // 转换IV和加密数据
    const iv = new Uint8Array(ivHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));
    const encrypted = new Uint8Array(encryptedHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));

    // 解密
    const decrypted = await crypto.subtle.decrypt(
      { name: 'AES-GCM', iv },
      cryptoKey,
      encrypted
    );

    // 转换为字符串
    return new TextDecoder().decode(decrypted);
  } catch (error) {
    console.error('Decryption error:', error);
    throw error;
  }
}

import { verify, decode } from '@tsndr/cloudflare-worker-jwt'

// 验证JWT token并解析用户信息
export async function verifyToken(token, secret) {
  try {
    const isValid = await verify(token, secret);
    if (isValid) {
      const decoded = decode(token);
      return { isValid: true, payload: decoded.payload };
    }
    return { isValid: false };
  } catch (error) {
    return { isValid: false };
  }
}

// 中间件：验证身份
export async function authenticate(request, env) {
  const authHeader = request.headers.get('Authorization')
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return new Response('Unauthorized', { status: 401 })
  }
  
  const token = authHeader.split(' ')[1]
  const { isValid, payload } = await verifyToken(token, env.JWT_SECRET)
  if (!isValid) {
    return new Response('Invalid token', { status: 401 })
  }

  // 将用户信息添加到request对象
  request.user = payload;
  return null
}